#include "View.h"

#include <SDL/Core/Renderer.h>

namespace SDL
{
    View::View(const Renderer &renderer)
        : pTexture(NULL), _x(0), _y(0), _w(0), _h(0), _borderSize(0), gRenderer(renderer.getSDLRenderer())
    {
    }

    View::~View()
    {
        if (pTexture == NULL)
        {
            SDL_DestroyTexture(pTexture);
            pTexture = NULL;
        }
    }
    void View::setSize(int w, int h)
    {
        _w = w;
        _h = h;
    }
    void View::setBorder(int borderSize) { _borderSize = borderSize; }
    void View::onDraw()
    {
        SDL_Color orginColor;
        SDL_GetRenderDrawColor(gRenderer, &orginColor.r, &orginColor.g, &orginColor.b, &orginColor.a);
        pTexture = SDL_CreateTexture(gRenderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_TARGET, _w, _h);
        SDL_SetRenderTarget(gRenderer, pTexture);
        SDL_SetRenderDrawColor(gRenderer, _backgroudcolor.r, _backgroudcolor.g, _backgroudcolor.b, _backgroudcolor.a);

        SDL_Rect rect = {0, 0, _w, _h};
        SDL_RenderDrawRect(gRenderer, &rect);
        SDL_SetRenderTarget(gRenderer, NULL);

        SDL_SetRenderDrawColor(gRenderer, orginColor.r, orginColor.g, orginColor.b, orginColor.a);
        SDL_Rect dstrect = {(int)(_x - (_w / 2)), (int)(_y - _h / 2), _w, _h};
        SDL_RenderCopy(gRenderer, pTexture, &rect, &dstrect);
    }
    void View::setPosition(int x, int y)
    {
        _x = x;
        _y = y;
    }
    void View::setBackgroudColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
    {
        _backgroudcolor.r = r;
        _backgroudcolor.g = g;
        _backgroudcolor.b = b;
        _backgroudcolor.a = a;
    }
} // namespace SDL
